package com.espressif.iot.command.device.plug;

import java.io.IOException;
import java.net.InetAddress;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.espressif.iot.base.api.EspBaseApiUtil;
import com.espressif.iot.base.net.rest.mesh.EspSocketClient;
import com.espressif.iot.type.device.status.IEspStatusPlug;

public class EspCommandPlugPostStatusLocal implements IEspCommandPlugPostStatusLocal
{
    
    private final static Logger log = Logger.getLogger(EspCommandPlugPostStatusLocal.class);
    

    @Override
    public String getLocalUrl(InetAddress inetAddress)
    {
        return "http://" + inetAddress.getHostAddress() + "/" + "config?command=switch";
    }
    
    private JSONObject getRequestJSONObject(IEspStatusPlug statusPlug)
    {
        JSONObject request = new JSONObject();
        JSONObject response = new JSONObject();
        try
        {
            int status = 0;
            if (statusPlug.isOn())
            {
                status = 1;
            }
            response.put(Status, status);
            request.put(Response, response);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        return request;
    }
    
    private boolean postPlugStatus(InetAddress inetAddress, IEspStatusPlug statusPlug, String deviceBssid, String router)
    {
        String uriString = getLocalUrl(inetAddress);
        JSONObject jsonObject;
        JSONObject result = null;
        jsonObject = getRequestJSONObject(statusPlug);
        if (deviceBssid == null || router == null)
        {
            result = EspBaseApiUtil.Post(uriString, jsonObject);
        }
        else
        {
            result = EspBaseApiUtil.PostForJson(uriString, router, deviceBssid, jsonObject);
        }
        return (result != null);
    }
    
    private boolean postPlugStatus2(InetAddress inetAddress, IEspStatusPlug statusPlug, String deviceBssid, boolean isMeshDevice)
    {
    	EspSocketClient mClient;
    	boolean  connetsuc=false;
    	String uriString = getLocalUrl(inetAddress);

        byte[] result ;
        byte[] senddata ;
        senddata = getRequestData(statusPlug, deviceBssid);
        
      
        	mClient = new EspSocketClient();
        	connetsuc = mClient.connect(inetAddress.getHostAddress(), 1206);
       if(connetsuc =false){
    	   try {
			Thread.sleep(500);
			connetsuc = mClient.connect(inetAddress.getHostAddress(), 1206);
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       }
       if(connetsuc =true)
       {
    	   try {
    	    	 //开始发送数据
    	    	String sendString=new String( senddata , "ISO-8859-1" );
    			mClient.writeRequest(sendString);
    			//开始接受数据进行判断处理
    			String ret =null;
    			
    			ret=	mClient.readResponse();
    			result = ret.getBytes( "ISO-8859-1" );
    			if(result.length ==  senddata.length){
    				int count = result.length;
    				if(result[count-1] == senddata[count-1] 
    						&& result[count-2] == senddata[count-3])
    				{
    					mClient.close();
    					mClient = null;
    					return true;
    				}
    			}
    			
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
       }
       
       if(mClient !=null){
		   try {
			mClient.close();
			mClient = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   }
	   return false;
    }
    
    private byte[] getRequestData(IEspStatusPlug statusPlug, String bssid) {
		// TODO Auto-generated method stub
    	String[] bssidtemp = bssid.split(":");
        byte[] senddat = new byte[PLUG_CTRL_LENGHT];
        senddat[0]=(byte)0xfe;
        senddat[1]=(byte)0xe7;
        senddat[2]=(byte)0x0;
        senddat[3]=(byte)0x0;
        senddat[4]=(byte)PLUG_CTRL_LENGHT-5;
        senddat[5]=(byte)Command_type.Set_DEV.ordinal();
        senddat[6]=Byte.parseByte(bssidtemp[0]);
        senddat[7]=Byte.parseByte(bssidtemp[1]);
        senddat[8]=Byte.parseByte(bssidtemp[2]);
        senddat[9]=Byte.parseByte(bssidtemp[3]);
        senddat[10]=Byte.parseByte(bssidtemp[4]);
        senddat[11]=Byte.parseByte(bssidtemp[5]);
        senddat[12]=Byte.parseByte(bssidtemp[6]);
        senddat[13]=Byte.parseByte(bssidtemp[7]);
          int status = 0;
             if (statusPlug.isOn())
             {
                 status = 1;
             }
             senddat[14]=(byte)status;    
         
         return senddat;
	}

	@Override
    public boolean doCommandPlugPostStatusLocal(InetAddress inetAddress, IEspStatusPlug statusPlug)
    {
        boolean result = postPlugStatus(inetAddress, statusPlug, null, null);
        log.debug(Thread.currentThread().toString() + "##doCommandPlugPostStatusInternet(inetAddress=[" + inetAddress
            + "],statusPlug=[" + statusPlug + "]): " + result);
        return result;
    }
    
    @Override
    public boolean doCommandPlugPostStatusLocal(InetAddress inetAddress, IEspStatusPlug statusPlug, String deviceBssid,
        String router)
    {
        boolean result = postPlugStatus(inetAddress, statusPlug, deviceBssid, router);
        log.debug(Thread.currentThread().toString() + "##doCommandPlugPostStatusLocal(inetAddress=[" + inetAddress
            + "],statusPlug=[" + statusPlug + "],deviceBssid=[" + deviceBssid + "],router=[" + router + "]): " + result);
        return result;
    }

    @Override
    public boolean doCommandPlugPostStatusLocal(InetAddress inetAddress, IEspStatusPlug statusPlug, String deviceBssid,
        boolean isMeshDevice)
    {
        boolean result = postPlugStatus2(inetAddress, statusPlug, deviceBssid, isMeshDevice);
        log.debug(Thread.currentThread().toString() + "##doCommandPlugPostStatusLocal(inetAddress=[" + inetAddress
            + "],statusPlug=[" + statusPlug + "],deviceBssid=[" + deviceBssid + "],router=[" + isMeshDevice + "]): "
            + result);
        return result;
    }
    
}
